<template>
  <div class="type-box">
    <div class="left-box">
      <div class="select-item">
        <span>算例类型</span>
        <el-select v-model="functionalModule" placeholder="请选择" style="width:260px;margin-left: 12px;">
          <el-option v-for="item in functionalModules" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="select-item">
        <span>数据分析 </span>
        <el-select v-model="analysisArea" style="width:260px;margin-left: 12px;">
          <el-option v-for="item in analysisAreas" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="right-box">
      <el-button text class="general-btn-action" @click="dataSubmit">数据提交</el-button>
      <el-button text class="general-btn-action" @click="visible = true">算例导入</el-button>
      <el-button text class="general-btn-action" @click="downloadFile">算例导出</el-button>
      <el-button text class="general-btn-action" @click="simulateAndVerify">{{ buttonText }}</el-button>
    </div>
  </div>
  <hr class="line" />
  <div class="bottom-box">
    <!-- <div class="demo-image">
        <div v-for="fit in fits" :key="fit" class="block">
          <el-image style="width: 640px; height: 500px;margin-left:30px;" :src="url" :fit="fit" />
        </div>
      </div> -->
    <div class="general-flex-center left-box">
      <img :src="url" class="img" />
    </div>
    <div :style="{ width: $computeVw(20) }"></div>
    <el-table :data="tableData"
      style="flex:1;height: 100%; --el-table-border-color: none;overflow-y: auto;border: #192E37;border: 1px solid #2F606B;box-sizing: border-box;"
      :row-class-name="getClassName" :header-cell-style="customHeaderCell" :cell-style="customCell">
      <el-table-column prop="name" label="名称" width="250" />
      <el-table-column prop="from_junction" label="连接点" width="120" />
      <el-table-column prop="basic_param" label="基础参数" />
    </el-table>

  </div>
  <!-- 文件上传 -->
  <el-dialog v-model="visible" :show-close='false' @close="handleDialogClose"
    style="background-color: #052733;width:500px;padding:0 10px 40px 30px;">
    <template #header="{ close, titleId, titleClass }">
      <div class="dialog-header">
        <h2 style="color:#fff">文件上传</h2>
        <el-icon color="#A3B5BB" :size="22" @click="close">
          <Close />
        </el-icon>
      </div>
    </template>
    <div>
      <!-- <input type="file" @change="onFileChange" />
        <el-button text @click="uploadFile">上传</el-button>
        <p v-if="uploadError">{{ uploadError }}</p>
        <p v-if="uploadSuccess">{{ uploadSuccess }}</p> -->
      <el-upload ref="upload" :on-change="handleFileChange" class="upload-demo" :multiple="true" :auto-upload="false"
        >
        <template #trigger>
          <div class="dialog-select-file">选择文件</div>
        </template>
        <el-button class="dialog-submit" type="success" @click="uploadFile">
          上传
        </el-button>
        <template #tip>
          <div class="el-upload__tip text-red" style="color:#00C3AC">
            <p v-if="uploadError">{{ uploadError }}</p>
            <p v-if="uploadSuccess">{{ uploadSuccess }}</p>
          </div>
        </template>
        <template #file="{ file }">
          <div class="dialog-upload-item" v-for="(f,index) in fileList" :key="index">{{ f.name }}</div>
        </template>
      </el-upload>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { computed, defineComponent, ref, watch } from "vue";
import { genFileId } from 'element-plus'
import type { ImageProps, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import axios from "axios";
import Dialog from "./Dialog.vue"
import { BASE_URL } from '@/utils/common.js'
import elTableMixin from '@/utils/elTableMixin.js'
import { Close } from '@element-plus/icons-vue'
import zongheImg from '@/assets/importImg/综合能源-其它.png';
import weiwangImg from '@/assets/importImg/微网群-其它.png';
import fenbushiImg from '@/assets/importImg/分布式协同-其它.png';
import fenbushiYuanHeImg from '@/assets/importImg/分布式协同-其它-源荷特性分析.png';
import fenbushiFenquImg from '@/assets/importImg/分布式协同-其它-分区.png';

const { customHeaderCell, customCell, getClassName } = elTableMixin();

const functionalModule = ref("");

const analysisArea = ref("");
// 下拉框初始化完毕 
// 下拉框赋值
const functionalModules = ref([
  // { value: "", label: "请选择" },
  { value: "microgrid", label: "微网群" },
  { value: "integrated_energy", label: "综合能源" },
  { value: "distributed_grid", label: "分布式协同电网" },
  // ... 其他功能模块
]);


const analysisAreas = ref([
  // { value: "partition", label: "分区" },
  // { value: "analysis", label: "源荷特征挖掘" },
]);

const selectedFunctionalModule = computed(() => {
  return functionalModules.value.find(item => item.value === functionalModule.value);
});

const selectedAnalysisArea = computed(() => {
  var selectedItem = analysisAreas.value.find(item => item.value === analysisArea.value)
  //console.log("第二个选择框当前的值是::"+selectedItem);
  return selectedItem
})

watch(functionalModule, (newVal, oldVal) => {
  console.log("param1是::" + newVal);
  if (newVal === "distributed_grid") {
    analysisAreas.value = [
       { value: "", label: "请选择" },
      { value: "partition", label: "分区" },
      { value: "analysis", label: "源荷特性分析" },
    ]
  } else {
    analysisAreas.value = []
    analysisArea.value = ''
  }
})

watch(analysisArea, async (newVal, oldVal) => {
  console.log("第二个选择框当前的值是::" + newVal);
  let app_url = BASE_URL + '/getCustomerFenbushi?input='
  if(isImport==1){
    if(newVal==='partition'){
        app_url +='partition'
        url.value = fenbushiFenquImg
    }else if(newVal==='analysis'){
       app_url += 'analysis'
       url.value = fenbushiYuanHeImg
    }
    if(newVal != ''){
       const response = await axios.get(app_url)
       tableData.value = response.data
    }
    
  }
})

const dataSubmit = async () => {
  const formData = new FormData();
  formData.append('functionModule', selectedFunctionalModule.value.label);

  if (selectedAnalysisArea.value) {
    console.log("点提交时，选择框二的值是：：" + selectedAnalysisArea.value.label)
    formData.append('analysis', selectedAnalysisArea.value.label);
  }
  //console.log("选择的值是::"+selectedFunctionalModule.value.label);
  try {
    const response = await axios.post(BASE_URL + '/getWeiwangqun', formData, {
      headers: {
        'Content-Type': 'application/json',
      },
    });
    console.log(response.data);
    tableData.value = response.data;
    if (selectedFunctionalModule.value.label == "微网群") {
      url.value = BASE_URL + "/getWeiwangImg";

    } else if (selectedFunctionalModule.value.label == "综合能源") {
      url.value = BASE_URL + "/getEnergyImg";
    } else if (selectedFunctionalModule.value.label == "分布式协同电网") {
      if (selectedAnalysisArea.value) {
        console.log("分网出错::" + selectedAnalysisArea.value.label);
        if (selectedAnalysisArea.value.label === "分区") {
          url.value = BASE_URL + "/getCollaborateArea";
        }
        if (selectedAnalysisArea.value.label === "源荷特性分析") {
          url.value = BASE_URL + "/getCollaborateLoad"
        }
        if (selectedAnalysisArea.value.label === "请选择") {
          url.value = BASE_URL + "/getCollaborateImg"
        }
      } else {
        url.value = BASE_URL + "/getCollaborateImg";
      }
    }
     
     isImport = 0;
  } catch (error) {
    console.error(error);
  }

}
// 仿真校验
const buttonText = ref('算例仿真校验')
function simulateAndVerify() {
  buttonText.value = '仿真校验中...'
  setTimeout(() => {
    alert('算例仿真校验成功');
    buttonText.value = '算例仿真校验'
  }, 3000)

}

//图片js
const fits = [
  'fill'

] as ImageProps['fit'][]
const url = ref(BASE_URL + "/getEmptyImg")
// 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'

console.log('url', url.value)
//表格
const tableData = ref([]);

// 文件上传弹窗
const visible = ref(false)

const selectedFile = ref([]);
const uploadError = ref('');
const uploadSuccess = ref('');
const upload = ref()

//新增的js逻辑

//覆盖前一个文件
const handleExceed: UploadProps['onExceed'] = (files) => {
  // upload.value!.clearFiles()
  for(let i=0;i<files.length;i++){
      let file = files[i] as UploadRawFile
      file.uid = genFileId()
      upload.value.push(file)
  }
  // const file = files[0] as UploadRawFile
  // file.uid = genFileId()
  // upload.value!.handleStart(file)
}

const handleFileChange = (files) => {
  // 选两个文件时 这个方法会进来两次
  // selectedFile.value = file?.raw
   selectedFile.value.push(files.raw); // 注意这里使用了 files[i].raw，确保你的文件对象有这个属性   
  uploadError.value = ''
  uploadSuccess.value = ''
}

//对话框关闭 清空选择及提示
const handleDialogClose = () => {
  upload.value?.clearFiles()
  selectedFile.value = [];
  uploadError.value = ''
  uploadSuccess.value = ''
}

// const onFileChange = (e) => {
//   selectedFile.value = e.target.files[0];
//   console.log('selectedFile.value', selectedFile.value)
// };
let isImport = 0;
const uploadFile = async () => {
  if(functionalModule.value===''){
    alert('请选择算例类型')
  }

  if (!selectedFile.value) {
    return alert('请先选择一个文件！');
  }

  const formData = new FormData();
  for(let i=0;i<selectedFile.value.length;i++){
     formData.append('file', selectedFile.value[i]);
  }

  try {
    const response = await axios.post(BASE_URL + '/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    uploadSuccess.value = response.data.message;
    uploadError.value = '';
    // 根据需要处理响应数据  
    //console.log(response.data);
    tableData.value = response.data.data;
    if(functionalModule.value==='microgrid'){
         url.value = weiwangImg;
    }else if(functionalModule.value==='integrated_energy'){
         url.value = zongheImg;
    }else if(functionalModule.value==='distributed_grid'){
         url.value = fenbushiImg
    }
    isImport = 1;
    analysisArea.value = ''
    handleDialogClose()
    visible.value = false
  } catch (error) {
    uploadError.value = '文件上传失败：' + error.message;
    uploadSuccess.value = '';
    console.error(error);
  }
};

//文件下载
const downloadFile = async () => {
  let fileUrl = ref(BASE_URL + '/download/')
  var fileName = ''
  if (selectedFunctionalModule.value.label == "微网群") {
    fileUrl.value += 'MicroGrid';
    fileName = 'CIGRE.json'
  } else if (selectedFunctionalModule.value.label == "综合能源") {
    fileUrl.value += 'energe'
    fileName = 'analysis.zip'
  } else {
    fileUrl.value += 'Distribute'
    fileName = 'net.json'
  }
  try {
    const response = await axios({
      method: 'get',
      url: fileUrl.value, // 你的后端下载接口  
      responseType: 'blob', // 表明服务器返回的数据类型  
    });

    // 创建一个 blob 对象  
    const url = window.URL.createObjectURL(new Blob([response.data]));
    // 创建一个a标签用于下载  
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName); // 设置下载文件名  
    document.body.appendChild(link);
    link.click(); // 模拟点击  
    // 然后移除这个元素  
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载文件失败:', error);
  }
}; 
</script>

<style scoped lang="scss">
.bottom-box {
  display: flex;
  flex: 1;
  justify-content: space-between;
  margin-top: computeVh(20);
  padding: 0 computeVw(16);
  overflow: hidden;

  .left-box {
    flex: 1;
    flex-shrink: 0;


    .img {
      max-width: 100%;
      max-height: 100%;
    }
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-select-file {
  width: computeVw(300);
  background-color: #fff;
  border-radius: 2px;
  padding: computeVh(8) computeVw(15);
  color: #00C3AC;
  margin-right: computeVw(10);
  cursor: pointer;
}

.dialog-submit {
  background-color: #00C3AC;
  border-radius: 0;
  border: none;
  margin-top: -2px;
}

.dialog-upload-item,
.dialog-upload-item:hover {
  font-size: computeVw(16);
  color: #fff;
  background-color: #052733 !important;
}

// :deep(.el-select) {
//   --el-color-primary: #00812d !important;
// }

.el-select .el-input .el-input__inner {
  color: red !important;
  /* 你想要的颜色 */
}

/* 当选中时的背景色 */
.el-select .el-input .el-input__inner:focus {
  border-color: red !important;
  /* 选中时的边框颜色 */
}

::v-deep .el-table__empty-block {
  width: 100% !important;
  height: computeVh(600) !important;
  font-size: computeVw(14);
  color: #FFFFFF !important;
}
</style>
